const OpenAI = require("openai");
const config = require("../config/base");
const pool = require("../config/database");

// 创建豆包 AI 实例
const doubaoAI = new OpenAI({
  apiKey: config.chat.doubao.apiKey,
  baseURL: "https://ark.cn-beijing.volces.com/api/v3",
});

// 创建 Deepseek AI 实例
const deepseekAI = new OpenAI({
  apiKey: config.chat.deepseek.apiKey,
  baseURL: "https://ark.cn-beijing.volces.com/api/v3", // 使用相同的火山引擎 API 地址
});

/**
 * 豆包 AI 对话
 * @param {*} prompt 问题文案
 */
async function doubaoAIChat(prompt) {
  console.log("调用豆包AI, 问题：", prompt);
  const completion = await doubaoAI.chat.completions.create({
    messages: [
      {
        role: "system",
        content: "你是豆包，是由字节跳动开发的 AI 人工智能助手",
      },
      {
        role: "user",
        content: prompt,
      },
    ],
    model: "ep-20250210154100-6b997",
  });
  return completion.choices[0].message.content;
}

/**
 * Deepseek AI 对话
 * @param {*} prompt 问题文案
 */
async function deepseekAIChat(prompt) {
  console.log("调用Deepseek AI, 问题：", prompt);
  const completion = await deepseekAI.chat.completions.create({
    messages: [
      {
        role: "system",
        content: "你是 Deepseek AI 助手，专注于提供专业、准确的回答",
      },
      {
        role: "user",
        content: prompt,
      },
    ],
    model: "ep-20250307111659-snxbq",
  });
  return completion.choices[0].message.content;
}

/**
 * 写入历史数据
 * @param {*} userId
 * @param {*} question
 * @param {*} answer
 */
async function insertChatHistory(userId, question, answer) {
  console.log("保存对话历史信息", userId, question, answer.slice(0, 100));
  const connection = await pool.getConnection();
  try {
    await connection.execute(
      "INSERT INTO chat_history (user_id, question, answer, created_at) VALUES (?,?,?, CONVERT_TZ(NOW(), '+00:00', '+08:00'))",
      [userId, question, answer]
    );
  } finally {
    connection.release();
  }
}

class ChatController {
  async chat(ctx) {
    const { prompt, model = 'doubao' } = ctx.request.body;
    const userId = ctx.state.user.id;

    try {
      if (!prompt) {
        ctx.status = 400;
        ctx.body = { error: "请输入内容" };
        return;
      }

      let result = "";
      if (model === "doubao") {
        result = await doubaoAIChat(prompt);
      } else if (model === "deepseek") {
        result = await deepseekAIChat(prompt);
      } else if (model === "doubao+deepseek") {
        const doubaoResponse = await doubaoAIChat(prompt);
        const deepseekResponse = await deepseekAIChat(prompt);
        const summaryResponse = await deepseekAIChat(
          `对于问题-${prompt}, 豆包回答：${doubaoResponse}, deepseek回答：${doubaoResponse}，基于上两个AI的回答，请给出一个综合的答案，要求1. 保持简洁明了、2. 突出重点内容、3. 确保逻辑连贯、4. 避免重复信息`
        );
        result = `豆包回答：\n${doubaoResponse}\nDeepseek回答：\n${deepseekResponse}\n总结后的回答：\n${summaryResponse}`;
      }

      // 对话数据写入数据库
      insertChatHistory(userId, prompt, result);

      ctx.body = {
        ok: true,
        msg: "success",
        data: result,
      };
    } catch (error) {
      console.error("AI 对话错误:", error);
      ctx.status = 500;
      ctx.body = { error: "AI 对话失败" };
    }
  }

  // 获取用户的对话历史
  async getHistory(ctx) {
    const userId = ctx.state.user.id;

    try {
      const connection = await pool.getConnection();
      try {
        const [rows] = await connection.execute(
          "SELECT * FROM chat_history WHERE user_id = ? ORDER BY created_at DESC",
          [userId]
        );
        ctx.body = {
          ok: true,
          msg: "success",
          data: rows,
        };
      } finally {
        connection.release();
      }
    } catch (error) {
      console.error("获取对话历史失败:", error);
      ctx.status = 500;
      ctx.body = { error: "获取对话历史失败" };
    }
  }

  // 删除对话
  async deleteChat(ctx) {
    const chatId = ctx.params.id;
    const userId = ctx.state.user.id;

    try {
      const connection = await pool.getConnection();
      try {
        await connection.execute(
          "DELETE FROM chat_history WHERE id = ? AND user_id = ?",
          [chatId, userId]
        );
        ctx.body = {
          ok: true,
          msg: "删除成功",
        };
      } finally {
        connection.release();
      }
    } catch (error) {
      console.error("删除对话失败:", error);
      ctx.status = 500;
      ctx.body = { error: "删除对话失败" };
    }
  }

  // 更新对话
  async updateChat(ctx) {
    const chatId = ctx.params.id;
    const userId = ctx.state.user.id;
    const { content } = ctx.request.body;

    try {
      // 1. 使用豆包 AI 获取第一个回答
      const doubaoResponse = await doubaoAI.chat.completions.create({
        messages: [{ role: "user", content }],
        model: "ep-20250210154100-6b997"  // 修正：使用正确的模型名称
      });

      // 2. 使用 Deepseek AI 获取第二个回答
      const deepseekResponse = await deepseekAI.chat.completions.create({
        messages: [{ role: "user", content }],
        model: "ep-20250307111659-snxbq"  // 修正：使用正确的模型名称
      });

      // 3. 将两个回答作为提示，生成最终回答
      const finalResponse = await deepseekAI.chat.completions.create({
        messages: [
          {
            role: "system",
            content: "你是一个智能助手，需要基于以下两个 AI 的回答，综合分析并给出最终的回答。"
          },
          {
            role: "user",
            content: `问题：${content}\n\n豆包回答：${doubaoResponse.choices[0].message.content}\n\nDeepseek回答：${deepseekResponse.choices[0].message.content}\n\n请综合以上两个回答，给出最终答案。`
          }
        ],
        model: "ep-20250307111659-snxbq"  // 修正：使用正确的模型名称
      });

      const finalAnswer = finalResponse.choices[0].message.content;

      // 4. 更新数据库，只保存最终的回答
      const connection = await pool.getConnection();
      try {
        await connection.execute(
          "UPDATE chat_history SET question = ?, answer = ? WHERE id = ? AND user_id = ?",
          [content, finalAnswer, chatId, userId]
        );

        ctx.body = {
          ok: true,
          msg: "更新成功",
          data: finalAnswer,
        };
      } finally {
        connection.release();
      }
    } catch (error) {
      console.error("更新对话失败:", error);
      ctx.status = 500;
      ctx.body = { error: "更新对话失败" };
    }
  }

  // 获取对话详情
  async getChatDetail(ctx) {
    const chatId = ctx.params.id;
    const userId = ctx.state.user.id;

    try {
      const connection = await pool.getConnection();
      try {
        const [rows] = await connection.execute(
          "SELECT * FROM chat_history WHERE id = ? AND user_id = ?",
          [chatId, userId]
        );

        if (rows.length === 0) {
          ctx.status = 404;
          ctx.body = {
            ok: false,
            error: "对话不存在",
          };
          return;
        }

        ctx.body = {
          ok: true,
          msg: "success",
          data: {
            id: rows[0].id,
            question: rows[0].question,
            answer: rows[0].answer,
            created_at: rows[0].created_at,
          },
        };
      } finally {
        connection.release();
      }
    } catch (error) {
      console.error("获取对话详情失败:", error);
      ctx.status = 500;
      ctx.body = {
        ok: false,
        error: "获取对话详情失败",
      };
    }
  }

  // 清除所有对话
  async clearAllChats(ctx) {
    const userId = ctx.state.user.id;

    try {
      const connection = await pool.getConnection();
      try {
        await connection.execute("DELETE FROM chat_history WHERE user_id = ?", [
          userId,
        ]);
        ctx.body = {
          ok: true,
          msg: "清除成功",
        };
      } finally {
        connection.release();
      }
    } catch (error) {
      console.error("清除对话失败:", error);
      ctx.status = 500;
      ctx.body = { error: "清除对话失败" };
    }
  }
}

module.exports = new ChatController();
